package middleware

import (
	"net/http"
	"wisdomCoach/utils"

	"github.com/gin-gonic/gin"
)

func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "没有权限,请先登录",
			})
			c.Abort()
			return
		}
		userId, err := utils.ParseJWT(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "token 已过期,请重新登录",
				"err":   err,
			})
			c.Abort()
			return
		}
		c.Set("userId", userId)
		c.Next()
	}
}
